#include "common.h"
#include "mmap_file_op.h"

using namespace std;
using namespace zsyuung_fs;

const static largefile::MMapOption mmap_option = {
    10240000,
    4096,
    4096
};

int main(void)
{
    const char* filename = "mmap_file_op.txt";
    largefile::MMapFileOperation mmfo(filename);

    int fd = mmfo.open_file();
    if(fd < 0)
    {
        fprintf(stderr, "open file %s failed, desc:%s\n", filename, strerror(-fd));
        exit(-1);
    }
    
    int ret = mmfo.mmap_file(mmap_option);
    if(ret == largefile::TFS_ERROR)
    {
        fprintf(stderr, "mmap_file failed, desc:%s\n", strerror(errno));
        mmfo.close_file();
        exit(-2);
    }

    char buffer[128 + 1];
    memset(buffer, '7', 128);

    ret = mmfo.pwrite_file(buffer, 128, 8);
    if(ret < 0)
    {
        if(ret == largefile::EXIT_DISK_OPER_INCOMPLETE)
        {
            fprintf(stderr, "pread_file: read_length is less than required\n");
        }
        else
        {
            fprintf(stderr, "mmap_file failed, desc:%s\n", strerror(errno));
        }
    }

    memset(buffer, 0, 128);
    ret = mmfo.pread_file(buffer, 128, 8);
    if(ret < 0)
    {
        if(ret == largefile::EXIT_DISK_OPER_INCOMPLETE)
        {
            fprintf(stderr, "pread_file: read_length is less than required\n");
        }
        else
        {
            fprintf(stderr, "mmap_file failed, desc:%s\n", strerror(errno));
        }
    }
    else
    {
        buffer[128] = '\0';
        printf("read:%s\n", buffer);
    }

    ret = mmfo.flush_file();
    if(ret == largefile::TFS_ERROR)
    {
        fprintf(stderr, "flush file failed, desc:%s\n", strerror(errno));
    }

    ret = mmfo.munmap_file();
    if(ret == largefile::TFS_ERROR)
    {
    
        fprintf(stderr, "munmap file failed\n");
    }

    mmfo.close_file();


    return 0;
}
